package cm.tl.pms.util;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 重复请求校验
 *
 * @author w7h1te_ywq
 * @version 1.0.0
 * @date 2023-11-03 11:57
 */
public class DuplicateRequestValidator {
    private static Set<String> processedRequests = new HashSet<>();

    // 自定义请求超时时间，默认为5分钟
    private static long requestTimeout = 5; // 单位：分钟

    // 设置请求超时时间
    public static void setRequestTimeout(long timeout) {
        requestTimeout = timeout;
    }

    // 判断请求是否已经处理过
    public static boolean isDuplicateRequest(String requestId) {
        synchronized (processedRequests) {
            return processedRequests.contains(requestId);
        }
    }

    // 处理请求并记录请求ID
    public static void recordRequestId(String requestId) {
        synchronized (processedRequests) {
            processedRequests.add(requestId);
        }

        // 定时清理请求ID
        scheduleRequestIdCleanUp(requestId);
    }

    // 定时清理请求ID
    private static void scheduleRequestIdCleanUp(String requestId) {
        long requestTimeoutMillis = TimeUnit.MINUTES.toMillis(requestTimeout);

        new Thread(() -> {
            try {
                Thread.sleep(requestTimeoutMillis);
                synchronized (processedRequests) {
                    processedRequests.remove(requestId);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}

